package com.example.launibleplugin.ui.components

import android.content.Intent
import android.provider.Settings
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.launibleplugin.LaUniBlePlugin
import com.example.launibleplugin.model.BluetoothDevice
import com.example.launibleplugin.utils.Logger
import com.google.gson.Gson

/**
 * 设备扫描选择组件
 * Function: 提供蓝牙设备扫描、列表显示和选择功能
 * Parameter: plugin - 蓝牙插件实例
 * Parameter: onDeviceSelected - 设备选择回调函数
 * Parameter: isInitialized - 插件是否已初始化
 * Note: 可复用的设备扫描组件，封装了完整的扫描流程
 */
@Composable
fun DeviceScannerComponent(
    plugin: LaUniBlePlugin,
    onDeviceSelected: (BluetoothDevice) -> Unit,
    isInitialized: Boolean,
    modifier: Modifier = Modifier
) {
    var isScanning by remember { mutableStateOf(false) }
    var discoveredDevices by remember { mutableStateOf(listOf<BluetoothDevice>()) }
    var scanStatusMessage by remember { mutableStateOf("准备扫描设备") }
    var debugInfo by remember { mutableStateOf("") }
    var showBluetoothDialog by remember { mutableStateOf(false) }
    
    val context = LocalContext.current
    
    // 设置扫描相关的事件监听器
    LaunchedEffect(Unit) {
        plugin.setEventCallback("onDeviceFound") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                if (data != null) {
                    val device = BluetoothDevice(
                        deviceId = data["deviceId"] as String,
                        deviceName = data["deviceName"] as? String,
                        macAddress = data["macAddress"] as String,
                        signalStrength = (data["signalStrength"] as Double).toInt()
                    )
                    discoveredDevices = discoveredDevices + device
                    scanStatusMessage = "发现设备: ${device.getDisplayName()}"
                }
            } catch (e: Exception) {
                Logger.e("DeviceScannerComponent", "解析设备发现事件失败", e)
            }
        }
        
        plugin.setEventCallback("onScanCompleted") { jsonData ->
            isScanning = false
            scanStatusMessage = "扫描完成，发现 ${discoveredDevices.size} 个设备"
            debugInfo = "扫描完成时间: ${System.currentTimeMillis()}"
        }
        
        plugin.setEventCallback("onScanStarted") { jsonData ->
            debugInfo = "扫描已启动，等待设备发现..."
        }
        
        plugin.setEventCallback("onScanFailed") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                val errorCode = data?.get("errorCode") as? Double
                val errorMessage = data?.get("message") as? String
                isScanning = false
                scanStatusMessage = "扫描失败: $errorMessage (错误码: $errorCode)"
                debugInfo = "扫描失败详情: $jsonData"
            } catch (e: Exception) {
                Logger.e("DeviceScannerComponent", "解析扫描失败事件异常", e)
                isScanning = false
                scanStatusMessage = "扫描失败"
                debugInfo = "解析错误: ${e.message}"
            }
        }
    }
    
    Card(
        modifier = modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = "设备扫描",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 扫描状态信息
            Text(
                text = scanStatusMessage,
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // 扫描控制按钮
            Button(
                onClick = {
                    if (!isScanning) {
                        // 开始扫描前检查权限
                        try {
                            val statusResult = plugin.checkBluetoothStatus()
                            val response = Gson().fromJson(statusResult, Map::class.java)
                            val success = response["success"] as? Boolean ?: false
                            
                            if (success) {
                                val data = response["data"] as? Map<String, Any>
                                if (data != null) {
                                    val bluetoothAvailable = data["bluetoothAvailable"] as? Boolean ?: false
                                    val hasPermissions = data["hasPermissions"] as? Boolean ?: false
                                    
                                    when {
                                        !bluetoothAvailable -> {
                                             // 蓝牙未开启，提示用户开启
                                             scanStatusMessage = "蓝牙未开启，请先开启蓝牙"
                                             showBluetoothDialog = true
                                             Logger.w("DeviceScannerComponent", "⚠️ 蓝牙未开启，显示设置对话框")
                                         }
                                        !hasPermissions -> {
                                            // 权限不足，提示用户授权
                                            scanStatusMessage = "权限不足，请授予蓝牙权限"
                                            Logger.w("DeviceScannerComponent", "⚠️ 蓝牙权限不足，无法开始扫描")
                                        }
                                        else -> {
                                            // 权限和蓝牙都正常，开始扫描
                                            discoveredDevices = emptyList()
                                            plugin.startScan()
                                            isScanning = true
                                            scanStatusMessage = "正在扫描设备..."
                                            Logger.i("DeviceScannerComponent", "🔍 开始扫描蓝牙设备")
                                        }
                                    }
                                } else {
                                    scanStatusMessage = "状态检查失败，数据格式异常"
                                }
                            } else {
                                val message = response["message"] as? String ?: "未知错误"
                                scanStatusMessage = "状态检查失败: $message"
                            }
                        } catch (e: Exception) {
                            Logger.e("DeviceScannerComponent", "检查蓝牙状态失败", e)
                            scanStatusMessage = "状态检查失败: ${e.message}"
                        }
                    } else {
                        // 停止扫描
                        plugin.stopScan()
                        isScanning = false
                        scanStatusMessage = "扫描已停止"
                        Logger.i("DeviceScannerComponent", "🛑 停止扫描蓝牙设备")
                    }
                },
                enabled = isInitialized,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(if (isScanning) "停止扫描" else "开始扫描")
            }
            
            // 设备列表
            if (discoveredDevices.isNotEmpty()) {
                Spacer(modifier = Modifier.height(16.dp))
                
                Text(
                    text = "发现的设备 (${discoveredDevices.size})",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Medium
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                LazyColumn(
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                    modifier = Modifier.heightIn(max = 300.dp)
                ) {
                    items(discoveredDevices) { device ->
                        DeviceListItem(
                            device = device,
                            onDeviceClick = { onDeviceSelected(device) }
                        )
                    }
                }
            }
            
            // 调试信息显示
            if (debugInfo.isNotEmpty()) {
                Spacer(modifier = Modifier.height(12.dp))
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.surfaceVariant
                    )
                ) {
                    Text(
                        text = "调试信息: $debugInfo",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.padding(8.dp)
                    )
                }
            }
            
            // 扫描提示和说明
            if (discoveredDevices.isEmpty() && !isScanning) {
                Spacer(modifier = Modifier.height(16.dp))
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.surfaceVariant
                    )
                ) {
                    Column(
                        modifier = Modifier.padding(12.dp)
                    ) {
                        Text(
                            text = "📱 扫描说明",
                            style = MaterialTheme.typography.titleSmall,
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Spacer(modifier = Modifier.height(4.dp))
                        Text(
                            text = "• 点击开始扫描按钮搜索附近的蓝牙设备",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = "• 🫁 呼吸家设备会特殊标识为目标设备",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = "• 点击连接按钮可连接到选中的设备",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }
            
            // 扫描结果统计
            if (discoveredDevices.isNotEmpty()) {
                Spacer(modifier = Modifier.height(8.dp))
                val respiratoryCount = discoveredDevices.count { it.isRespiratoryDevice() }
                Text(
                    text = if (respiratoryCount > 0) {
                        "🎯 发现 $respiratoryCount 个呼吸家设备，共 ${discoveredDevices.size} 个设备"
                    } else {
                        "⚠️ 未发现呼吸家设备，共扫描到 ${discoveredDevices.size} 个设备"
                    },
                    style = MaterialTheme.typography.bodySmall,
                    color = if (respiratoryCount > 0) {
                        MaterialTheme.colorScheme.primary
                    } else {
                        MaterialTheme.colorScheme.onSurfaceVariant
                    },
                    fontWeight = if (respiratoryCount > 0) FontWeight.Medium else FontWeight.Normal
                )
            }
            
        }
    }
}

/**
 * 设备列表项组件
 * Function: 显示单个蓝牙设备的信息
 * Parameter: device - 蓝牙设备对象
 * Parameter: onDeviceClick - 设备点击回调
 * Note: 设备列表的子组件，呼吸家设备会特殊标识
 */
@Composable
private fun DeviceListItem(
    device: BluetoothDevice,
    onDeviceClick: () -> Unit
) {
    val isRespiratoryDevice = device.isRespiratoryDevice()
    
    Card(
        onClick = onDeviceClick,
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = if (isRespiratoryDevice) {
                MaterialTheme.colorScheme.primaryContainer
            } else {
                MaterialTheme.colorScheme.surface
            }
        ),
        border = if (isRespiratoryDevice) {
            BorderStroke(2.dp, MaterialTheme.colorScheme.primary)
        } else null
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp)
        ) {
            // 设备类型标签
            if (isRespiratoryDevice) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(bottom = 4.dp)
                ) {
                    Surface(
                        color = MaterialTheme.colorScheme.primary,
                        shape = RoundedCornerShape(4.dp),
                        modifier = Modifier.padding(end = 8.dp)
                    ) {
                        Text(
                            text = "目标设备",
                            color = MaterialTheme.colorScheme.onPrimary,
                            style = MaterialTheme.typography.labelSmall,
                            modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp)
                        )
                    }
                    Text(
                         text = device.getDeviceTypeLabel(),
                         style = MaterialTheme.typography.labelMedium,
                         color = MaterialTheme.colorScheme.primary,
                         fontWeight = FontWeight.Bold
                     )
                }
            } else {
                Text(
                     text = device.getDeviceTypeLabel(),
                     style = MaterialTheme.typography.labelMedium,
                     color = MaterialTheme.colorScheme.onSurfaceVariant,
                     modifier = Modifier.padding(bottom = 4.dp)
                 )
            }
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(
                    modifier = Modifier.weight(1f)
                ) {
                    Text(
                        text = device.getDisplayName(),
                        fontWeight = if (isRespiratoryDevice) FontWeight.Bold else FontWeight.Medium,
                        style = MaterialTheme.typography.bodyMedium,
                        color = if (isRespiratoryDevice) {
                            MaterialTheme.colorScheme.onPrimaryContainer
                        } else {
                            MaterialTheme.colorScheme.onSurface
                        }
                    )
                    Text(
                        text = "MAC: ${device.macAddress}",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "信号: ${device.getSignalStrengthDescription()}",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = "${device.signalStrength} dBm",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
                
                Button(
                    onClick = onDeviceClick,
                    modifier = Modifier.padding(start = 8.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = if (isRespiratoryDevice) {
                            MaterialTheme.colorScheme.primary
                        } else {
                            MaterialTheme.colorScheme.secondary
                        }
                    )
                ) {
                    Text(
                        text = if (isRespiratoryDevice) "连接设备" else "连接",
                        style = MaterialTheme.typography.labelMedium
                    )
                }
            }

        }
    }
}